<?php

class cMatrix
{
	public $xsize;
	public $ysize;
	
	public $data = array();
	
	public function __construct($xsize,$ysize,$build = true)
	{
		$this->xsize = $xsize;
		$this->ysize = $ysize;

		if($build)
			$this->build();
	}

	protected function build()
	{
		for($y=0;$y<$this->ysize;$y++)
			for($x=0;$x<$this->xsize;$x++)
				$this->set($x,$y,0);			
	}
	
	public function get($x,$y)
	{
		if(!isset($this->data[$y][$x]))
			return 0;
		
		return $this->data[$y][$x];
	}
	
	public function set($x,$y,$value)
	{
		return $this->data[$y][$x] = $value;
	}
	
	public function alter($x,$y,$offset)
	{
		return $this->data[$y][$x] += $offset;
	}
	
	public static function add(cMatrix $m1,cMatrix $m2)
	{
		if($m1->xsize != $m2->xsize || $m1->ysize != $m2->ysize)
			throw new Exception("Matrix Size Issue");
		
		$matrix = new cMatrix($m1->xsize,$m1->ysize);

		for($y=0;$y<$matrix->ysize;$y++)
			for($x=0;$x<$matrix->xsize;$x++)
				$matrix->set($x,$y,$m1->get($x,$y) + $m2->get($x,$y));
				
		return $matrix;
	}
	
	public static function sub(cMatrix $m1,cMatrix $m2)
	{
		if($m1->xsize != $m2->xsize || $m1->ysize != $m2->ysize)
			throw new Exception("Matrix Size Issue");
		
		$matrix = new cMatrix($m1->xsize,$m1->ysize);

		for($y=0;$y<$matrix->ysize;$y++)
			for($x=0;$x<$matrix->xsize;$x++)
				$matrix->set($x,$y,$m1->get($x,$y) - $m2->get($x,$y));
				
		return $matrix;
	}	

	public static function scale(cMatrix $m1,$scalar)
	{	
		$matrix = new cMatrix($m1->xsize,$m1->ysize);

		for($y=0;$y<$matrix->ysize;$y++)
			for($x=0;$x<$matrix->xsize;$x++)
				$matrix->set($x,$y,$m1->get($x,$y) * $scalar);
				
		return $matrix;
	}
	
	public static function neg(cMatrix $m1)
	{	
		$matrix = new cMatrix($m1->xsize,$m1->ysize);

		for($y=0;$y<$matrix->ysize;$y++)
			for($x=0;$x<$matrix->xsize;$x++)
				$matrix->set($x,$y,-$m1->get($x,$y));
				
		return $matrix;		
	}
	
	public static function mul(cMatrix $m1,cMatrix $m2)
	{
		if($m1->xsize != $m2->ysize)
			throw new Exception("Matrix Size Issue");
			
		$matrix = new cMatrix($m2->xsize,$m1->ysize);

		for($mx=0;$mx<$m1->ysize;$mx++)
			for($my=0;$my<$m2->xsize;$my++)
			{
				//echo "$mx,$my == ";
				$value = 0;
				for($c=0;$c<$m1->xsize;$c++)
				{
					$value += $m1->get($c,$mx) * $m2->get($my,$c);
					//echo $c.", ".$mx." x ".$my.", ".$c." + ";
				}
				//echo "\n";		
				$matrix->set($my,$mx,$value);
			}
			//echo "\n";
		
		return $matrix;
	}
	
	public function __toString()
	{
		$output = "";
		for($i=0;$i<$this->ysize;$i++)
			$output .= implode(", ",$this->data[$i])."\n";
			
		return $output;
	}
}

?>